package com.wgts.wgts.mvp.view.activity.tasklobby;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.ClipboardManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hjq.permissions.XXPermissions;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.wgts.wgts.ActivityStack;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.dialog.ToastDate;
import com.wgts.wgts.control.dialog.ToastDialogFragment;
import com.wgts.wgts.control.dialog.WonderLoadingDialog;
import com.wgts.wgts.control.eventbus.TaskDetailsEventBus;
import com.wgts.wgts.control.recycleview.CustomLineaLayoutManager;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerWgtsTaskDetailsActivityComponent;
import com.wgts.wgts.dagger.module.WgtsTaskDetailsActivityModule;
import com.wgts.wgts.mvp.presenter.IWgtsTaskDetailsActivityPresenter;
import com.wgts.wgts.mvp.view.IWgtsTaskDetailsActivityView;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.netmodle.AppOkHttpClient;
import com.wgts.wgts.netmodle.DownloadFile;
import com.wgts.wgts.netmodle.resp.TaskDetailEntity;
import com.wgts.wgts.react.MD5Util;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.CustomImageView;
import com.wgts.wgts.tools.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/*
 *
 *
 */
@RuntimePermissions
public class WgtsTaskDetailsActivity extends BaseActivity implements IWgtsTaskDetailsActivityView {
    @Inject
    IWgtsTaskDetailsActivityPresenter presenter;
    @BindView(R.id.back_btn_image)
    ImageView backBtnImage;
    @BindView(R.id.back_btn_ly)
    LinearLayout backBtnLy;
    @BindView(R.id.include_title)
    TextView includeTitle;
    @BindView(R.id.include_text)
    TextView includeText;
    @BindView(R.id.include_right_image)
    ImageView includeRightImage;
    @BindView(R.id.include_right_ly)
    LinearLayout includeRightLy;
    @BindView(R.id.task_status_text)
    TextView taskStatusText;
    @BindView(R.id.task_name)
    TextView taskName;
    @BindView(R.id.task_number)
    TextView taskNumber;
    @BindView(R.id.task_time)
    TextView taskTime;
    @BindView(R.id.task_description_text)
    TextView taskDescriptionText;
    @BindView(R.id.task_description_details_text)
    TextView taskDescriptionDetailsText;
    @BindView(R.id.copy_task_text)
    LinearLayout copyTaskText;
    @BindView(R.id.save_image_button)
    LinearLayout saveImageButton;
    @BindView(R.id.task_image_recycle)
    RecyclerView taskImageRecycle;
    @BindView(R.id.submit_task_ly)
    LinearLayout submitTaskLy;
    @BindView(R.id.issue_task_ly)
    LinearLayout issueTaskLy;
    @BindView(R.id.video_view)
    JCVideoPlayerStandard videoView;
    @BindView(R.id.video_picture)
    TextView videoPicture;
    @BindView(R.id.submit_task_text)
    TextView submitTaskText;
    @BindView(R.id.issue_task_text)
    TextView issueTaskText;
    @BindView(R.id.net_error_ly)
    LinearLayout netErrorLy;

    private TaskImageAdapter adapter;

    private String url, videoPath;

    public static final String TASK_TITLE = "title";
    //每日任务是否达到上限
    public static final String TASK_TYPE = "taskType";
    public static final String TASK_ID = "taskId";
    private TaskDetailEntity taskDetailEntity;
    //进入详情页的入口类别
    public static final String COME_TYPE = "comeType";
    //任务大厅(只有进行中状态)
    public static final String LOBBY = "lobby";
    //我参与的及提交任务成功
    public static final String JOIN_AND_COMMIT = "joinAndCommit";

    private WonderLoadingDialog dialog;

    private String type, comeType;
    private boolean taskType;
    private int taskId;
    private String taskRole = "";

    public static final int VERTIFY_TASK = 0x111;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wgts_task_details_activity);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        includeTitle.setText("任务详情");
        initView();
    }

    @Override
    public void init() {
        DaggerWgtsTaskDetailsActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .wgtsTaskDetailsActivityModule(new WgtsTaskDetailsActivityModule(this))
                .build()
                .inject(this);
    }

    private void initView() {
        comeType = getIntent().getStringExtra(COME_TYPE);
        taskId = getIntent().getIntExtra(TASK_ID, 0);
        taskType = getIntent().getBooleanExtra(TASK_TYPE, false);
        dialog = new WonderLoadingDialog(WgtsTaskDetailsActivity.this);
        dialog.mLoadingText = "正在保存";
        showDialog();
        switch (comeType) {
            case LOBBY:
                presenter.initDate(taskId);
                break;
            case JOIN_AND_COMMIT:
                presenter.joinTaskDetailsDate(taskId);
                break;
        }
    }

    @Override
    public void onError(int status, String msg) {
        if (status != VERTIFY_TASK){
            netErrorLy.setVisibility(View.VISIBLE);
        }
        dialogDismiss();
        MoHuToast.showToast(msg);
    }

    @OnClick({R.id.back_btn_ly, R.id.copy_task_text, R.id.save_image_button, R.id.submit_task_ly,
            R.id.issue_task_ly, R.id.net_error_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn_ly:
                finish();
                break;
            case R.id.copy_task_text:
                ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(taskDescriptionDetailsText.getText().toString()); //将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可
                MoHuToast.showToast("复制成功");
                break;
            case R.id.save_image_button:
                if (type != null) {
                    if (type.equals("VIDEO")) {
                        WgtsTaskDetailsActivityPermissionsDispatcher.saveVideoWithPermissionCheck(this);
                    } else {
                        WgtsTaskDetailsActivityPermissionsDispatcher.saveShareImgWithPermissionCheck(this);
                    }
                }
                break;
            case R.id.submit_task_ly:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
                    presenter.vertifyTask(taskDetailEntity.userTaskId);
                } else {
                    Intent intent2 = new Intent(this, LoginActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.issue_task_ly:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")) {
                    switch (taskRole) {
                        case "VIP":
                            if (AppInfor.getInstance().getUserState() < 1) {
                                showToastDialog("您还不是金牌推手，请前去升级");
                            } else {
                                showDialog();
                                presenter.issueTask(taskDetailEntity.id, taskDetailEntity.taskCode, "");
                            }
                            break;
                        case "SVIP":
                            if (AppInfor.getInstance().getUserState() < 2) {
                                showToastDialog("您还不是钻石推手，请前去升级");
                            } else {
                                showDialog();
                                presenter.issueTask(taskDetailEntity.id, taskDetailEntity.taskCode, "");
                            }
                            break;
                    }
                } else {
                    Intent intent2 = new Intent(this, LoginActivity.class);
                    startActivity(intent2);
                }
                break;
            case R.id.net_error_ly:
                switch (comeType) {
                    case LOBBY:
                        presenter.initDate(taskId);
                        break;
                    case JOIN_AND_COMMIT:
                        presenter.joinTaskDetailsDate(taskId);
                        break;
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        try {
            JCVideoPlayer.releaseAllVideos();
        } catch (Exception e) {
        }
    }

    @Override
    public void onBackPressed() {
        if (videoView.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoView.releaseAllVideos();
    }

    @Override
    public void initDate(TaskDetailEntity entity) {
        netErrorLy.setVisibility(View.GONE);
        dialogDismiss();
        taskDetailEntity = entity;
        taskTime.setText(entity.beginTime + "~" + entity.endTime);
        taskName.setText(entity.produceName + entity.taskName);
        taskNumber.setText(entity.taskCode);
        type = entity.detailType;
        taskDescriptionDetailsText.setText(entity.detail);
        taskRole = entity.taskType;
        switch (entity.detailType) {
            case "VIDEO":
                videoPicture.setText("视频");
                taskImageRecycle.setVisibility(View.GONE);
                videoView.setVisibility(View.VISIBLE);
                CustomImageView.getInstance().customView(this, videoView, 9 / (double) 16);
                videoView.setUp(entity.url.get(0).filePath, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, entity.taskName);
                videoView.thumbImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                url = entity.url.get(0).filePath;
                videoPath = entity.url.get(0).fileName;
                Glide.with(this).load(R.mipmap.video_plcaholder).into(videoView.thumbImageView);
                break;
            case "PICTURE":
                videoPicture.setText("图片");
                taskImageRecycle.setVisibility(View.VISIBLE);
                videoView.setVisibility(View.GONE);
                CustomLineaLayoutManager layoutManager = new CustomLineaLayoutManager(this);
                taskImageRecycle.setLayoutManager(layoutManager);
                adapter = new TaskImageAdapter(this, entity.url);
                taskImageRecycle.setAdapter(adapter);
                break;
        }
        switch (entity.taskType) {
            case "VIP":
                taskStatusText.setText("金牌推手任务");
                break;
            case "SVIP":
                taskStatusText.setText("钻石推手任务");
                break;
        }
        switch (entity.status) {
            case "PENDING":
                if (taskType) {
                    submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                    submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                    submitTaskLy.setClickable(false);
                    issueTaskLy.setBackgroundResource(R.drawable.wgts_submit_border);
                    issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.white));
                    issueTaskLy.setClickable(true);
                } else {
                    submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                    submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                    submitTaskLy.setClickable(false);
                    issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                    issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                    issueTaskLy.setClickable(false);
                }
                break;
            case "ACTIVE":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_submit_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.white));
                submitTaskLy.setClickable(true);
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;
        }
    }

    @Override
    public void issueResult(Integer entity) {
        dialogDismiss();
        MoHuToast.showToast("任务领取成功");

        TaskDetailsEventBus eventBus = new TaskDetailsEventBus();
        eventBus.setId(entity);
        EventBus.getDefault().post(eventBus);

        presenter.joinTaskDetailsDate(entity);
    }

    @Override
    public void vertifyTask() {
        Intent intent = new Intent(WgtsTaskDetailsActivity.this, SubmitTaskActivity.class);
        intent.putExtra(SubmitTaskActivity.TYPE, "submit");
        intent.putExtra(COME_TYPE, comeType);
        intent.putExtra(SubmitTaskActivity.SUBMIT_TASK_ID, taskDetailEntity.userTaskId);
        intent.putExtra(SubmitTaskActivity.TASK_ID, taskDetailEntity.id);
        startActivity(intent);
    }

    @Override
    public void joinTaskDetail(TaskDetailEntity entity) {
        netErrorLy.setVisibility(View.GONE);
        dialogDismiss();
        taskDetailEntity = entity;
        taskTime.setText(entity.beginTime + "~" + entity.endTime);
        taskName.setText(entity.produceName + entity.taskName);
        taskNumber.setText(entity.taskCode);
        type = entity.detailType;
        taskDescriptionDetailsText.setText(entity.detail);
        taskRole = entity.taskType;
        switch (entity.detailType) {
            case "VIDEO":
                videoPicture.setText("视频");
                taskImageRecycle.setVisibility(View.GONE);
                videoView.setVisibility(View.VISIBLE);
                CustomImageView.getInstance().customView(this, videoView, 9 / (double) 16);
                CustomImageView.getInstance().customView(this, videoView.thumbImageView, 9 / (double) 16);
                videoView.setUp(entity.url.get(0).filePath, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, entity.taskName);
                url = entity.url.get(0).filePath;
                break;
            case "PICTURE":
                videoPicture.setText("图片");
                taskImageRecycle.setVisibility(View.VISIBLE);
                videoView.setVisibility(View.GONE);
                CustomLineaLayoutManager layoutManager = new CustomLineaLayoutManager(this);
                taskImageRecycle.setLayoutManager(layoutManager);
                adapter = new TaskImageAdapter(this, entity.url);
                taskImageRecycle.setAdapter(adapter);
                break;
        }
        switch (entity.taskType) {
            case "VIP":
                taskStatusText.setText("金牌推手任务");
                break;
            case "SVIP":
                taskStatusText.setText("钻石推手任务");
                break;
        }
        switch (entity.status) {
            case "ACTIVE":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_submit_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.white));
                submitTaskLy.setClickable(true);
                submitTaskText.setText("提交任务");
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;
            case "DONE":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                submitTaskLy.setClickable(false);
                submitTaskText.setText("已完成");
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;
            case "INVALID":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                submitTaskLy.setClickable(false);
                submitTaskText.setText("提交任务");
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;
            case "FAILED":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                submitTaskLy.setClickable(false);
                submitTaskText.setText("未达标");
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;
            case "AUDIT":
                submitTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                submitTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                submitTaskLy.setClickable(false);
                submitTaskText.setText("审核中");
                issueTaskLy.setBackgroundResource(R.drawable.wgts_login_border);
                issueTaskText.setTextColor(ContextCompat.getColor(this, R.color.hint_6));
                issueTaskLy.setClickable(false);
                issueTaskText.setText("已领取");
                break;

        }

    }

    private void showToastDialog(String showText) {
        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion(showText);
        toastDate.setCancelText("取消");
        toastDate.setPointText("去升级");
        final ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getSupportFragmentManager(), "upLevel");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                fragment.dismiss();
                goToUpLevel();
                finish();
                fragment.dismiss();
            }

            @Override
            public void onClickEnsuer() {
                fragment.dismiss();
            }
        });
    }

    private void goToUpLevel() {
        for (Activity activity : ActivityStack.getInstance().getActivities()) {
            if (activity != null && activity instanceof MoHuMainActivity) {
                ((MoHuMainActivity) activity).upLevel();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TaskDetailsEventBus event) {
        presenter.joinTaskDetailsDate(event.getId());
    }


    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void saveShareImg() {
        if (dialog != null) {
            dialog.show();
        }
        for (int i = 0; i < adapter.getImageView().size(); i++) {
            Tools.KeepBitmap(adapter.getImageView().get(i), this);
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        MoHuToast.showToast("保存成功");
    }

    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void saveVideo() {
        DownloadFile downloadFile = new DownloadFile(AppOkHttpClient.getInstance().getOkHttpClient());
        String[] urlSplit = videoPath.split("\\.");
        final String path = Environment.getExternalStorageDirectory() + File.separator + "DCIM"
                + File.separator + "Camera" + File.separator + MD5Util.encrypt(videoPath) + "." + urlSplit[urlSplit.length - 1];
        downloadFile.downLoadVideo(url, path, new FileDownloadLargeFileListener() {
            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                if (dialog != null) {
                    dialog.show();
                }
            }

            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                MoHuToast.showToast("保存成功");
                File videoPath = new File(path);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(videoPath)));
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                MoHuToast.showToast("保存失败，请重试");
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                MoHuToast.showToast("保存成功");
                File videoPath = new File(path);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(videoPath)));
            }
        });
    }

    @OnPermissionDenied({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void permissionDenied() {
        MoHuToast.showToast("您已拒绝了相应权限，保存图片失败");
    }

    @OnNeverAskAgain({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void askAgain() {
        ToastDate toastDate = new ToastDate();
        toastDate.setCancelQuestion("拒绝权限部分功能将不能使用，请去设置打开权限");
        toastDate.setCancelText("去设置");
        toastDate.setPointText("取消");
        toastDate.setFragmentManager(getSupportFragmentManager());
        ToastDialogFragment fragment = ToastDialogFragment.setToastMessage(toastDate);
        fragment.show(getSupportFragmentManager(), "");
        fragment.setOnClickListener(new ToastDialogFragment.OnClickListener() {
            @Override
            public void onClickCancle() {
                MoHuToast.showToast("您已拒绝了相应权限，保存图片失败");
            }

            @Override
            public void onClickEnsuer() {

                XXPermissions.gotoPermissionSettings(WgtsTaskDetailsActivity.this);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        WgtsTaskDetailsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
